package com.rose.ware.ware.service.impl;


import com.alibaba.fastjson.TypeReference;
import com.rabbitmq.client.Channel;
import com.rose.common.enume.OrderStatusEnum;
import com.rose.common.to.mq.OrderTo;
import com.rose.common.to.mq.StockDetailTo;
import com.rose.common.to.mq.StockLockedTo;

import com.rose.common.utils.R;
import com.rose.ware.ware.entity.WareOrderTaskDetailEntity;
import com.rose.ware.ware.entity.WareOrderTaskEntity;
import com.rose.ware.ware.exception.NoStockException;
import com.rose.ware.ware.feign.OrderFeignService;
import com.rose.ware.ware.service.WareOrderTaskDetailService;
import com.rose.ware.ware.service.WareOrderTaskService;
import com.rose.ware.ware.vo.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rose.common.utils.PageUtils;
import com.rose.common.utils.Query;

import com.rose.ware.ware.dao.WareSkuDao;
import com.rose.ware.ware.entity.WareSkuEntity;
import com.rose.ware.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
//@RabbitListener(queues = "stock.release.stock.queue")专门写了一个linstener
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Resource
    WareSkuDao wareSkuDao;
    @Autowired
    private OrderFeignService orderFeignService;

    @Autowired
    WareOrderTaskService orderTaskService;//工作订单

    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;

    @Value("${myRabbitmq.MQConfig.eventExchange}")
    private String eventExchange;

    @Value("${myRabbitmq.MQConfig.routingKey}")
    private String routingKey;

//    @RabbitHandler
//    @Override
//    public void unlockStock(StockLockedTo to) {
//        log.info("\n收到解锁库存的消息");
//        // 库存id
//        //库存工作单的id
//        Long id = to.getId();
//        StockDetailTo detailTo = to.getDetailTo();
//        Long detailId = detailTo.getId();
//        /**
//         * 解锁库存
//         * 	查询数据库关系这个订单的详情
//         * 		有: 证明库存锁定成功
//         * 			1.没有这个订单, 必须解锁
//         * 			2.有这个订单 不是解锁库存
//         * 				订单状态：已取消,解锁库存
//         * 				没取消：不能解锁	;
//         * 		没有：就是库存锁定失败， 库存回滚了 这种情况无需回滚
//         */
//        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
//        if(byId != null){
//            // 解锁
//            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
//            String orderSn = taskEntity.getOrderSn();
//            // 根据订单号 查询订单状态 已取消才解锁库存
//            R orderStatus = orderFeignService.getOrderStatus(orderSn);
//            if(orderStatus.getCode() == 0){
//                // 订单数据返回成功
//                OrderVo orderVo = orderStatus.getData(new TypeReference<OrderVo>() {});
//                // 订单不存在
//                if(orderVo == null || orderVo.getStatus() == OrderStatusEnum.CANCLED.getCode()){
//                    // 订单已取消 状态1 已锁定  这样才可以解锁
//                    if(byId.getLockStatus() == 1){
//                        unLock(detailTo.getSkuId(), detailTo.getWareId(), detailTo.getSkuNum(), detailId);
//                        //需要ack机制来完善
//                        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//                    }
//                }
//            }else{
//                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
//                // 消息拒绝 重新放回队列 让别人继续消费解锁
////                throw new RuntimeException("远程服务失败");
//            }
//        }else{
//            // 无需解锁
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//        }
//
//    }

    @Override
    public void unlockStock(StockLockedTo to) {
        log.info("\n收到解锁库存的消息");
        // 库存id
        Long id = to.getId();
        StockDetailTo detailTo = to.getDetailTo();
        Long detailId = detailTo.getId();
        /**
         * 解锁库存
         * 	查询数据库关系这个订单的详情
         * 		有: 证明库存锁定成功
         * 			1.没有这个订单, 必须解锁
         * 			2.有这个订单 不是解锁库存
         * 				订单状态：已取消,解锁库存
         * 				没取消：不能解锁	;
         * 		没有：就是库存锁定失败， 库存回滚了 这种情况无需回滚
         */
        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
        if(byId != null){
            // 解锁
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            // 根据订单号 查询订单状态 已取消才解锁库存
            R orderStatus = orderFeignService.getOrderStatus(orderSn);
            if(orderStatus.getCode() == 0){
                // 订单数据返回成功
                OrderVo orderVo = orderStatus.getData(new TypeReference<OrderVo>() {});
                System.out.println("WareSkuServiceImpl===>"+orderVo.getStatus());
                // 订单不存在
                if(orderVo == null || orderVo.getStatus() == OrderStatusEnum.CANCLED.getCode()){
                    // 订单已取消 状态1 已锁定  这样才可以解锁
                    if(byId.getLockStatus() == 1){
                        unLock(detailTo.getSkuId(), detailTo.getWareId(), detailTo.getSkuNum(), detailId);
                    }
                }
            }else{
                // 消息拒绝 重新放回队列 让别人继续消费解锁
                throw new RuntimeException("远程服务失败");
            }
        }else{
            // 无需解锁
        }
    }


    @Transactional
    @Override
    public void unlockStock(OrderTo to) {
        log.info("\n订单超时自动关闭,准备解锁库存");
        String orderSn = to.getOrderSn();
        // 查一下最新的库存状态 防止重复解锁库存[Order服务可能会提前解锁]
        WareOrderTaskEntity taskEntity = orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long taskEntityId = taskEntity.getId();
        // 按照工作单找到所有 没有解锁的库存 进行解锁 状态为1等于已锁定
        List<WareOrderTaskDetailEntity> entities = orderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", taskEntityId)
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : entities) {
            unLock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum(), entity.getId());
        }
    }

//    private void unLock(Long skuId, Long wareId, Integer skuNum, Long detailId) {
//    }

    /**
     * 解锁库存
     * @param skuId 解锁哪个商品
     * @param wareId 在哪个库存
     * @param num 数量
     * @param taskDeailId
     */
    private void unLock(Long skuId,Long wareId, Integer num, Long taskDeailId){
        // 更新库存
        wareSkuDao.unlockStock(skuId, wareId, num);
        // 更新库存工作单的状态
        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(taskDeailId);
        detailEntity.setLockStatus(2);
        orderTaskDetailService.updateById(detailEntity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        return skuIds.stream().map(id -> {
            SkuHasStockVo stockVo = new SkuHasStockVo();

            // 查询当前sku的总库存量
            stockVo.setSkuId(id);
            // 这里库存可能为null 要避免空指针异常
            stockVo.setHasStock(baseMapper.getSkuStock(id)==null?false:true);
            return stockVo;
        }).collect(Collectors.toList());
    }

    /**
     * 默认是运行时异常都会回滚
     * 为某个订单锁定库存
     * @param vo
     * @return
     */
    @Transactional(rollbackFor=NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        /**
         * 保存库存工作单的详情
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        orderTaskService.save(taskEntity);

        //1.按照下单的收获地址，找到就近的一个仓库，锁定库存
        //2.找到每个商品在那个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> skuWareHasStocks = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            List<Long> wareIds = wareSkuDao.listWareIdHasStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        Boolean allLock = true;
        for (SkuWareHasStock hasStock : skuWareHasStocks) {
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if(wareIds == null || wareIds.size() == 0){
                //没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }
            // 如果每一个商品都锁定成功 将当前商品锁定了几件的工作单记录发送给MQ
            // 如果锁定失败 前面保存的工作单信息回滚了
            for (Long wareId : wareIds) {
                //成功就返回1 否则返回0
                Long count = wareSkuDao.lockSkuStock(skuId,wareId,hasStock.getNum());
                if(count ==1){
                    skuStocked = true;
                    //TODO 告诉mq库存锁定成功
                    WareOrderTaskDetailEntity taskDetailEntity =
                            new WareOrderTaskDetailEntity(null,skuId,"",hasStock.getNum(),taskEntity.getId(),wareId,1);
                    orderTaskDetailService.save(taskDetailEntity);
                    //构造中间件消息
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(taskEntity.getId());

                    StockDetailTo detailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity, detailTo);
                    // 防止回滚以后找不到数据 把详细信息页
                    stockLockedTo.setDetailTo(detailTo);

                    rabbitTemplate.convertAndSend(eventExchange, routingKey ,stockLockedTo);
                    break;
                }else{
                    //当前仓库锁失败，重试下一个仓库
                }
            }
            if(skuStocked ==false){
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);

            }
        }
        //3.肯定全部都是锁定成功的

        return true;
    }

    @Data
    class SkuWareHasStock{

        private Long SkuId;
        private List<Long> wareId;
        private Integer num;

     }


}